package czk.concrent.syn;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/5/10 19:36
 */
public class SellTickets {
    public static void main(String[] args) throws InterruptedException {
        TicketWindow window=new TicketWindow(10000);
        // 记录售出总数 vector为线程安全集合
        List<Integer> sellCountList=new Vector<>();
        // 存储线程，等待线程join 主线程才运行
        List<Thread> threadList=new LinkedList<>();
        for (int i = 0; i <100 ; i++) {
            Thread thread=new Thread(()->{
                int count = window.sellCount(window.getSellCount());
                sellCountList.add(count);
            });
            threadList.add(thread);
            thread.start();
        }
        // 等待线程join
        for (Thread thread : threadList) {
            thread.join();
        }
        // 得到剩余剩余票数
        System.out.println("剩余的票数为"+window.getCount());
        // 得到卖出去的数
        long count = sellCountList.stream().mapToInt(i -> i).sum();
        System.out.println("卖出去的票数为  "+count);
    }
}
class TicketWindow{
    int count;
    public  TicketWindow(int count){
        this.count=count;
    }
    public int getCount(){
        return count;
    }
    // 售票
    public synchronized int sellCount(int sellCount){
        if (count>sellCount){
            count=count-sellCount;
            return sellCount;
        }
        int i=count;
        count=0;
        return i;
    }
    // 获得随机卖票数
    public int getSellCount(){
        return  new Random().nextInt(200);
    }
}
